package com.markerhub.controller;


import com.markerhub.common.lang.Result;
import com.markerhub.entity.Ins;

import com.markerhub.repository.InsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/ins")
public class InsController {

//
//
//    @GetMapping("/info/{id}")//查
//    @PreAuthorize("hasAuthority('ins:list')")
//    public Result info(@PathVariable("id") Long id) {
//        Ins ins =insService.getById(id);
//        return Result.succ(ins);
//    }
//
//
//
//    @PostMapping("/save")
//    @PreAuthorize("hasAuthority('ins:save')")
//    public Result save(@Validated @RequestBody(required=false) Ins ins) {
//
//        insService.save(ins);//增
//        return Result.succ(ins);
//    }
//
//
//    @PostMapping("/update")
//    @PreAuthorize("hasAuthority('ins:update')")
//    public Result update(@Validated @RequestBody Ins ins) {
//
//        insService.save(ins);//改
//        return Result.succ(ins);
//    }

//    @PostMapping("/delete")
//    @PreAuthorize("hasAuthority('ins:delete')")
//    public Result info(@RequestBody Long[] ids) {
//
//
//        return Result.succ();//删
//    }

    @Autowired
    private InsRepository insRepository;

    @GetMapping("/findAll/{page}/{size}")
    public Page<Ins> findAll(@PathVariable("page") Integer page, @PathVariable("size") Integer size) {
        PageRequest request = PageRequest.of(page -1, size);
        return insRepository.findAll(request);
    }

    @PostMapping("/save")
    public String save(@RequestBody Ins ins) {
        System.out.println(ins);
        Ins result = insRepository.save(ins);
        if (result != null) {
            return "success";
        } else {
            return "error";
        }
    }



    @GetMapping("/findById/{id}")
    public Ins findById(@PathVariable("id")  Integer id)
    {
        return  insRepository.findById(id).get();
    }

    @PutMapping("/update")
    public String update(@RequestBody Ins ins){
        Ins result=insRepository.save(ins);
        if (result != null) {
            return "success";
        } else {
            return "error";
        }
    }
    @GetMapping("/findByName/{name}")
    public List<Ins> findByName(@PathVariable("name") String name){
//        Ins ins=insRepository.findByName(name);

        List<Ins> insList = insRepository.findByName(name);
        System.out.println(insList);
        return insList;
    }

    @DeleteMapping("/deleteById/{id}")
    public void deleteById(@PathVariable("id")  Integer id){
        insRepository.deleteById(id);
    }


}
